package com.knoya.chejian.pda.module.packageTurnover

import android.app.ActivityManager
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.util.Log
import android.view.View
import com.knoya.chejian.pda.R
import com.knoya.chejian.pda.activity.BaseActivity
import com.knoya.chejian.pda.minterface.OnUserDataInterface
import com.knoya.chejian.pda.myadapter.PackageTurnoverAdapter
import com.knoya.chejian.pda.util.FileUtils
import com.knoya.chejian.pda.util.JsonUtil
import com.knoya.chejian.pda.util.Myutil
import kotlinx.android.synthetic.main.activity_package_turnover.*
import kotlinx.android.synthetic.main.header_knoya.*
import org.json.JSONException
import org.json.JSONObject

class PackageTurnoverActivity : BaseActivity(), View.OnClickListener {


    lateinit var dialog: AlertDialog
    lateinit var pcodes : ArrayList<PackageTurnoverBean>
    lateinit var chukupcodes : ArrayList<PackageTurnoverBean>
    lateinit var yuanpcodes : ArrayList<PackageTurnoverBean>
    lateinit var chukuadapter : PackageTurnoverAdapter
    var issao = false
    lateinit var M : PackageTurnoverM
    var issaoyunxu = true
    override fun getLayoutId(): Int {
//        when(jiemian){
//            1 -> return R.layout.activity_chuku
//            2 -> return R.layout.activity_chuku_2
//        }
        return R.layout.activity_package_turnover
    }

    override fun initCreate() {
        iv_header_left.visibility = View.VISIBLE
        iv_header_left.setOnClickListener(this)
        tv_header_title.text = "周转"
        M = PackageTurnoverM()
        Bt_Chuku_Ok.setOnClickListener(this)
        Bt_Xiazai.setOnClickListener(this)
        Bt_Kaishi_Chuku.setOnClickListener(this)
//        Bt_Saomiao.setOnClickListener(this)

        pcodes = ArrayList<PackageTurnoverBean>()
        yuanpcodes = ArrayList<PackageTurnoverBean>()
        chukupcodes = ArrayList<PackageTurnoverBean>()

        chukuadapter = PackageTurnoverAdapter(pcodes,this)
        Lv_pcode.adapter = chukuadapter

        tv_header_title.isFocusable = true
        tv_header_title.isFocusableInTouchMode = true
        tv_header_title.requestFocus()
        tv_header_title.requestFocusFromTouch()

        mBoradcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if(!isAPPBroughtToBackground()){
                    return
                }
                if(!issaoyunxu){
                    return
                }
                if (intent.action == "nlscan.action.SCANNER_RESULT" && intent.hasExtra("SCAN_BARCODE1")) {
                    val scanResult_1 = intent.getStringExtra("SCAN_BARCODE1").trim()
                    samiaoOk(scanResult_1)
                }
                if(intent.action == "android.intent.ACTION_DECODE_DATA" && intent.hasExtra("barcode_string")){
                    val scanResult = intent.getStringExtra("barcode_string").trim()
                    samiaoOk(scanResult)
                }
                if(intent.action == "com.qs.scancode"){
                    val scanResult = intent.extras.getString("data").trim()
                    samiaoOk(scanResult)
                }
            }
        }
        Et_Pcode.setOnEditorActionListener { _, actionId, _ ->
            var isOK = true
            isOK
        }
    }

    //扫描获取到数据后处理
    fun samiaoOk(data : String){
        var d = data;
        if(data.length>28){
            var ss = data.split("#")
            if(ss.size > 1){
                d = ss[1]
            }
        }
        if(d.length>28){
            Myutil.tishidialog(this@PackageTurnoverActivity,"条码扫描错误，请重新扫描")
            Myutil.zhendong(this)
            FileUtils.playSound(R.raw.baojing);
        }
        if(issao) {
            ispcodes(d)
            chukuadapter.notifyDataSetChanged()
        }else{
            Et_Pcode.setText(d)
        }
    }

    private fun ispcodes(pcode :String) {
        Log.d("TAAG",pcode)
        for (bean in chukupcodes){
            if(pcode == bean.pcode){
                Myutil.MyTost("这包货已经扫描过")
                return
            }
        }
        for (bean  in pcodes){
            if(pcode == bean.pcode){
                chukupcodes.add(bean)
                pcodes.remove(bean)
                zongbaoshu()
                return
            }
        }
        issaoyunxu = false
        Myutil.tishidismissdialog(this, "没找到条码$pcode",object : DialogInterface.OnDismissListener{
            override fun onDismiss(dialog: DialogInterface?) {
                issaoyunxu = true
            }
        })
    }

    private fun zongbaoshu(){
        var daichuku = 0
        var yisaomiao = 0
        var weisaomiao = 0
        yisaomiao = chukupcodes.size
        for (bean in yuanpcodes){
            if(bean.status == "未周转"){
                daichuku++
            }
        }
        weisaomiao = daichuku - yisaomiao
        Tv_tishi.text = "待周转： "+daichuku+" 未扫描:"+weisaomiao+" 已扫描："+yisaomiao
    }

    override fun onClick(v: View?) {
        when(v){
//            Bt_Saomiao -> {
//                samiaoOk(Et_Pcode.text.toString().trim())
//            }
            iv_header_left -> {
                finish()
            }
            Bt_Chuku_Ok -> {
                if(chukupcodes.size == 0){
                    Myutil.tishidialog(this,"录入条码后才能周转")
                    return
                }
                if(!issao){
                    Myutil.tishidialog(this,"开始周转后才能周转")
                    return
                }
                dialog = Myutil.showupdatedialog(this@PackageTurnoverActivity, "正在更新周转数据", false)
                M.package_turnover(this,chukupcodes,object : OnUserDataInterface {
                    override fun onUserData(data: String?) {
                        if(data == null){
                            return
                        }
                        Log.d("TAAAG",data)
                        var status = ""
                        var msg = ""
                        try {
                            var jo = JSONObject(data)
                            status = JsonUtil.getvolue(jo,"status")
                            msg = JsonUtil.getvolue(jo ,"msg")
                        }catch (e : JSONException){
                            e.printStackTrace()
                        }
                        if(msg != ""){
                            Myutil.tishidialog(this@PackageTurnoverActivity,msg)
                        }
                        dialog.dismiss()
                        if(status != "success"){
                            return
                        }
                        Bt_Kaishi_Chuku.text = "开始周转"
                        issao = false
                        chukupcodes.clear()
                    }

                    override fun onNot(throwable: String?) {
                        Log.d("TAAAG",throwable.toString())
                        dialog.dismiss()
                    }

                })
            }
            Bt_Xiazai -> {
                dialog = Myutil.showupdatedialog(this@PackageTurnoverActivity, "正在获取数据", false)
                M.getdata(this@PackageTurnoverActivity,Et_Pcode.text.toString().trim(),object :
                    OnUserDataInterface {
                    override fun onUserData(data: String?) {
                        dialog.dismiss()
                        if(data == null){
                            return
                        }
                        Myutil.longlogshow("TAAAG", Myutil.decodeUnicode(data))
                        jsondata(data)
                    }

                    override fun onNot(throwable: String?) {
                        dialog.dismiss()
                        Log.d("TAAAG",throwable.toString())
                    }
                })
            }
            Bt_Kaishi_Chuku -> {
                if(issao){
                    Bt_Kaishi_Chuku.text = "开始周转"
                    issao = false
                    chukupcodes.clear()
                    pcodes.clear()
                    for (bean in yuanpcodes){
                        pcodes.add(bean)
                    }
                }else{
                    issao = true
                    Bt_Kaishi_Chuku.text = "停止周转"
                }
            }
        }
    }

    fun jsondata(data : String){
        yuanpcodes.clear()
        pcodes.clear()
        var status = ""
        var msg = ""
        try {
            var jo = JSONObject(data)
            status = JsonUtil.getvolue(jo,"status")
            var js = JsonUtil.getjsvolue(jo,"data")
            msg = JsonUtil.getvolue(jo ,"msg")
            for(i in 0 until js.length()){
                var pcodejo = js[i] as JSONObject
                var bean = PackageTurnoverBean()
                bean.pcode = JsonUtil.getvolue(pcodejo,"pcode")
                bean.pt_time = JsonUtil.getvolue(pcodejo,"pt_ctime")
                bean.status = JsonUtil.getvolue(pcodejo,"status")
                yuanpcodes.add(bean)
            }
        }catch (e : JSONException){
            e.printStackTrace()
            Log.d("TAAG",e.toString())
        }

        if(status == "success"){
            for (bean in yuanpcodes){
                pcodes.add(bean)
            }
            chukuadapter.notifyDataSetChanged()
        }else if(status == "error"){
        }
        zongbaoshu()
        if(msg != ""){
            Myutil.tishidialog(this,msg)
        }
        dialog.dismiss()
    }

    fun isAPPBroughtToBackground(): Boolean {
        val am = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val tasks = am.getRunningTasks(1)
        if (!tasks.isEmpty()) {
            val topActivity = tasks[0].topActivity
            if (topActivity.className == this.javaClass.name) {

                return true
            }
        }
        return false
    }
}
